<?php

/**
 * JingYao-backend
 *
 * @link     https://gitee.com/wang-zhihui-release/jingyao-backend
 * @apiDocument https://gitee.com/wang-zhihui-release/jingyao-backend/wikis/
 */

namespace App\Replaces\Redis;

use Illuminate\Redis\Connections\PhpRedisConnection;
use OpenTracing\GlobalTracer;

class ReplacePhpRedisConnection extends PhpRedisConnection
{
    public function __construct($client, callable $connector = null, array $config = [])
    {
        parent::__construct($client, $connector, $config);
    }

    public function get($key)
    {
        return $this->track(function () use ($key) {
            return parent::get($key);
        }, __FUNCTION__, $key);
    }

    public function set($key, $value, $expireResolution = null, $expireTTL = null, $flag = null)
    {
        return $this->track(function () use ($key, $value, $expireResolution, $expireTTL, $flag) {
            return parent::set($key, $value, $expireResolution, $expireTTL, $flag);
        }, __FUNCTION__, $key);
    }

    private function track(callable $callback, string $type, string $key)
    {
        if (config('app.env') !== 'test') {
            return $callback();
        }
        $tracer = GlobalTracer::get();
        $activeSpan = $tracer->getActiveSpan();
        $startTime = microtime(true);
        $res = $callback();
        $endTime = microtime(true);
        $span = $tracer->startSpan('redis.' . $type, [
            'child_of' => $activeSpan->getContext(),
            'start_time' => (int)($startTime * 1000 * 1000),
        ]);
        $span->setTag('redis.key', $key);
        $span->setTag('redis.client_time', $endTime - $startTime);
        $span->finish();
        return $res;
    }
}
